package com.group9.controller;

import com.alibaba.fastjson.JSONArray;
import com.group9.dto.*;
import com.group9.pojo.*;
import com.group9.service.CommentMessageServer;
import com.group9.service.CommentMessageService;
import com.group9.service.CommentService;
import com.group9.service.ExtraInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import sun.java2d.pipe.AAShapePipe;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Created by Lcouncillor on 2020/6/6.
 */
@Controller
@RequestMapping(value = "comment")
public class CommentController {

    @Autowired
    ExtraInfoService extraInfoService;

    @Autowired
    CommentService commentService;

    @Autowired
    CommentMessageService commentMessageService;

    @Autowired
    CommentMessageServer commentMessageServer;

    /**
     * 仅评论内容上传
     */
    @RequestMapping(value = "onlycontent")
    @ResponseBody
    public String addResourceCommentContent(Comment comment, HttpSession session){

//        String userId = (String)session.getAttribute("customerId");
        String userId = "1001";

        //获取用户信息
        CustomerInfo customerInfo = extraInfoService.showCustomerInfoByUserId(userId);
        //获取水果信息
        FruitInfo fruitInfo= extraInfoService.showFruitInfoByFruitId(comment.getResourceId());

        //将获得的信息填入一级评论表中
        ResourceComment resourceComment = new ResourceComment();
        resourceComment.setSenderId(userId);
        resourceComment.setSenderName(customerInfo.getLoginName());
        resourceComment.setSenderPic(customerInfo.getOther2());
        resourceComment.setResourceId(comment.getResourceId());
        resourceComment.setResourceName(fruitInfo.getFruitName());
        resourceComment.setCommentStar(comment.getCommentStar());
        resourceComment.setCommentContent(comment.getCommentContent());
        resourceComment.setThumbUpAmount(0);
        resourceComment.setCommentTime(new Date());

        commentService.addFirstLevelComment(resourceComment);

        return resourceComment.getId();
    }

    /**
     * 如果评论有图片上传，执行完addResourceCommentContent()，在执行此方法
     */
    @RequestMapping(value = "/addcomment")
    @ResponseBody
    public String addResourceCommentPic(Comment comment){
        //存储图片到本地
        String name =  comment.getCommentPic().getOriginalFilename();
        String fileName = UUID.randomUUID() + name.substring(name.lastIndexOf("."));
        File file = new File(fileName);
        try {
            comment.getCommentPic().transferTo(file);
        } catch (IOException e) {
            e.printStackTrace();
        }

        //将图片存到mongodb
        String pic = "http://localhost:8080/img/"+fileName;

        Integer result = commentService.saveFirstLevelCommentPic(comment.getResourceCommentId(),pic);

        if (result == 1){
            return "success";
        }else {
            return "fail";
        }
    }

    /**
     * 按时间倒序展示当前页信息
     * @param resourceId
     * @param currentPage
     * @return
     */
    @RequestMapping(value = "/showcomment")
    @ResponseBody
    public PageInfo getPageInfo(Integer resourceId,Integer currentPage){
        return commentService.showFirstLevelCommentByIdAndLimit(resourceId, currentPage);
    }

    @RequestMapping(value = "/resourcecomment")
    @ResponseBody
    public ResourceComment getResourceComment(String commentId){
        System.out.println(commentId);
        return commentService.showResourceCommentById(commentId);
    }

    /**
     * 获取userId
     * @param session
     * @return
     */
    @RequestMapping(value = "/getuserid")
    @ResponseBody
    public String getUserId(HttpSession session){
//        String userId= (String) session.getAttribute("customerId");
        return "1001";
    }


    /**
     * 点赞或取消赞
     * @param session
     * @return
     */
    @RequestMapping(value = "/thumbup")
    @ResponseBody
    public void thumbUp(HttpSession session, String id){
//        String userId= (String) session.getAttribute("customerId");
        String userId =  "1001";
        commentService.saveCommentThumbUp(id,userId);
    }

    /**
     * 添加二级评论
     * @param session
     * @param id
     * @param content
     * @return
     */
    @RequestMapping(value = "/addresponse")
    @ResponseBody
    public String addSecondCommentResponse(HttpSession session, String id, String content){
        //        String userId= (String) session.getAttribute("customerId");
        String userId =  "1003";

        CommentResponse commentResponse = new CommentResponse();
        commentResponse.setSenderId(userId);
        CustomerInfo customerInfo = extraInfoService.showCustomerInfoByUserId(userId);
        commentResponse.setSenderName(customerInfo.getLoginName());
        commentResponse.setResponseContent(content);
        commentResponse.setParentId(id);

        int result = commentService.addSecondLevelComment(commentResponse);


        if ( result == 1){

            //添加到消息库
            CommentMessage commentMessage = new CommentMessage();
            commentMessage.setSenderId(commentResponse.getSenderId());
            commentMessage.setSenderName(commentResponse.getSenderName());
            ResourceComment resourceComment = commentService.showResourceCommentById(id);
            commentMessage.setReceiverId(resourceComment.getSenderId());
            commentMessage.setReceiverName(resourceComment.getSenderName());
            commentMessage.setContent(content);
            commentMessage.setCommentId(id);
            commentMessage.setCommentSenterName(resourceComment.getSenderName());
            commentMessage.setStatus(1);

            commentMessageService.addCommentMessage(commentMessage);
            commentService.commentMessageAlert(resourceComment.getSenderId());

            return "success";
        }

        return "fail";
    }

    /**
     * 通过一级评论id查找到对应的二级评论
     * @param id
     * @return
     */
    @RequestMapping(value = "/showresponse")
    @ResponseBody
    public List<CommentResponse> showSecondCommentResponse(String id){

        ResourceComment resourceComment = commentService.showResourceCommentById(id);
        String[] responses = resourceComment.getResponseId();
        if (responses == null){
            return null;
        }

        List<CommentResponse> commentResponses = new ArrayList<>();

        for (int i=0; i<responses.length; i++){
            CommentResponse commentResponse = commentService.showCommentResponseById(responses[i]);
            commentResponses.add(commentResponse);
        }

        return commentResponses;
    }

    /**
     * 添加三级评论
     * @param session
     * @param id
     * @param content
     * @return
     */
    @RequestMapping(value = "/addreply")
    @ResponseBody
    public String addThirdCommentResponse(HttpSession session, String id, String content){
        //String userId= (String) session.getAttribute("customerId");
        String userId =  "1002";

        CommentResponse commentResponse2 = commentService.showCommentResponseById(id);

        CommentResponse commentResponse = new CommentResponse();
        commentResponse.setSenderId(userId);
        commentResponse.setReceiverId(commentResponse2.getSenderId());
        commentResponse.setReceiverName(commentResponse2.getSenderName());
        CustomerInfo customerInfo = extraInfoService.showCustomerInfoByUserId(userId);
        commentResponse.setSenderName(customerInfo.getLoginName());
        commentResponse.setResponseContent(content);
        commentResponse.setParentId(id);

        int result = commentService.addThirdLevelComment(commentResponse);


        if ( result == 1){

            //添加到消息库
            CommentMessage commentMessage = new CommentMessage();
            commentMessage.setSenderId(commentResponse.getSenderId());
            commentMessage.setSenderName(commentResponse.getSenderName());
            ResourceComment resourceComment = commentService.showResourceCommentById(commentResponse2.getParentId());
            commentMessage.setReceiverId(commentResponse2.getSenderId());
            commentMessage.setReceiverName(commentResponse2.getSenderName());
            commentMessage.setContent(content);
            commentMessage.setCommentId(resourceComment.getId());
            commentMessage.setCommentSenterName(resourceComment.getSenderName());
            commentMessage.setStatus(1);

            commentMessageService.addCommentMessage(commentMessage);

            commentService.commentMessageAlert(commentMessage.getReceiverId());

            return "success";
        }

        return "fail";
    }


    /**
     * 通过二级评论id找到对于三级评论
     * @param id
     * @return
     */
    @RequestMapping(value = "/showreply")
    @ResponseBody
    public List<CommentResponse> showThirdCommentResponse(String id){

        CommentResponse commentResponse = commentService.showCommentResponseById(id);
        String[] responses = commentResponse.getResponseId();
        if (responses == null){
            return null;
        }

        List<CommentResponse> commentResponses = new ArrayList<>();

        for (int i=0; i<responses.length; i++){
            CommentResponse commentResponse1 = commentService.showCommentResponseById(responses[i]);
            commentResponses.add(commentResponse1);
        }

        return commentResponses;
    }

    /**
     * 根据一级评论展示所有相关的二级三级评论
     * @param id
     * @return
     */
    @RequestMapping(value = "/showallresponse")
    @ResponseBody
    public List<AllResponseComment> showAllCommentResponse(String id){
        List<CommentResponse> commentResponse2 = showSecondCommentResponse(id);
        List<AllResponseComment> allResponseComments = new ArrayList<>();
        for (int i=0;i<commentResponse2.size(); i++){
            AllResponseComment allResponseComment = new AllResponseComment();
            allResponseComment.setId(commentResponse2.get(i).getId());
            allResponseComment.setSenderId(commentResponse2.get(i).getSenderId());
            allResponseComment.setSenderName(commentResponse2.get(i).getSenderName());
            allResponseComment.setSenderPic(commentResponse2.get(i).getSenderPic());
            allResponseComment.setReceiverId(commentResponse2.get(i).getReceiverId());
            allResponseComment.setReceiverName(commentResponse2.get(i).getReceiverName());
            allResponseComment.setResponseContent(commentResponse2.get(i).getResponseContent());
            allResponseComment.setParentId(commentResponse2.get(i).getParentId());
            allResponseComment.setCommentTime(commentResponse2.get(i).getCommentTime());

            List<CommentResponse> commentResponses3 = showThirdCommentResponse(commentResponse2.get(i).getId());

            if ( commentResponses3 != null && !commentResponses3.isEmpty()){
                CommentResponse[] commentResponses = new CommentResponse[commentResponses3.size()];
                for (int j=0; j<commentResponses3.size(); j++){
                    commentResponses[j] = commentResponses3.get(j);
                }
                allResponseComment.setResponses(commentResponses);
            }

            allResponseComments.add(allResponseComment);
        }

        return allResponseComments;
    }

    /**
     * 添加三级评论的回复（也是三级评论）
     * @param session
     * @param id
     * @param content
     * @return
     */
    @RequestMapping(value = "/addnewreply")
    @ResponseBody
    public String addThirdCommentReply(HttpSession session, String id, String content){
        //String userId= (String) session.getAttribute("customerId");
        String userId =  "1004";

        //获取评论对象的parentId
        CommentResponse commentResponse3 = commentService.showCommentResponseById(id);
        String parentId = commentResponse3.getParentId();

        CommentResponse commentResponse = new CommentResponse();
        commentResponse.setReceiverId(commentResponse3.getSenderId());
        commentResponse.setReceiverName(commentResponse3.getSenderName());
        commentResponse.setSenderId(userId);
        CustomerInfo customerInfo = extraInfoService.showCustomerInfoByUserId(userId);
        commentResponse.setSenderName(customerInfo.getLoginName());
        commentResponse.setResponseContent(content);
        commentResponse.setParentId(parentId);

        int result = commentService.addThirdLevelComment(commentResponse);

        System.out.println(result);

        if ( result == 1){
            //添加到消息库
            CommentMessage commentMessage = new CommentMessage();
            commentMessage.setSenderId(commentResponse.getSenderId());
            commentMessage.setSenderName(commentResponse.getSenderName());
            //父级评论为二级评论
            CommentResponse commentResponse2 = commentService.showCommentResponseById(parentId);
            //二级评论的父级才为一级评论
            ResourceComment resourceComment = commentService.showResourceCommentById(commentResponse2.getParentId());
            commentMessage.setReceiverId(commentResponse3.getSenderId());
            commentMessage.setReceiverName(commentResponse3.getSenderName());
            commentMessage.setContent(content);
            commentMessage.setCommentId(resourceComment.getId());
            commentMessage.setCommentSenterName(resourceComment.getSenderName());
            commentMessage.setStatus(1);

            commentMessageService.addCommentMessage(commentMessage);

            //消息提示
            commentService.commentMessageAlert(commentMessage.getReceiverId());

            return "success";
        }
        return "fail";
    }


    /**
     * 显示未读评论消息
     * @return
     */
    @RequestMapping(value = "/message")
    @ResponseBody
    public List<CommentMessages> showIsExistMessage(){
        //String userId= (String) session.getAttribute("customerId");
        String userId =  "1001";
        return commentMessageService.showNoReadMessage(userId);
    }


    /**
     * 显示已读评论消息
     * @return
     */
    @RequestMapping(value = "/readedmessage")
    @ResponseBody
    public List<CommentMessages> showReadedMessage(){
        //String userId= (String) session.getAttribute("customerId");
        String userId =  "1001";
        System.out.println(commentMessageService.showReadedMessage(userId));
        return commentMessageService.showReadedMessage(userId);
    }


}
